<template>
  <div class="tasks-container">
    <div class="tasks-header">
      <h1>任务管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索任务"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearchClear"
          style="width: 250px; margin-right: 15px;"
        />
        <el-button type="primary" @click="showCreateTaskDialog">创建新任务</el-button>
      </div>
    </div>

    <div class="tasks-filters">
      <el-select v-model="filterProject" placeholder="项目筛选" clearable style="width: 180px; margin-right: 15px;">
        <el-option
          v-for="project in projects"
          :key="project.id"
          :label="project.name"
          :value="project.id"
        />
      </el-select>
      <el-select v-model="filterStatus" placeholder="状态筛选" clearable style="width: 150px; margin-right: 15px;">
        <el-option label="未开始" value="未开始" />
        <el-option label="进行中" value="进行中" />
        <el-option label="已完成" value="已完成" />
        <el-option label="已暂停" value="已暂停" />
      </el-select>
      <el-select v-model="filterPriority" placeholder="优先级筛选" clearable style="width: 150px; margin-right: 15px;">
        <el-option label="低" value="低" />
        <el-option label="中" value="中" />
        <el-option label="高" value="高" />
        <el-option label="紧急" value="紧急" />
      </el-select>
      <el-select v-model="filterAssignee" placeholder="负责人筛选" clearable style="width: 180px;">
        <el-option
          v-for="member in members"
          :key="member.id"
          :label="member.name"
          :value="member.name"
        />
      </el-select>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredTasks"
      style="width: 100%"
      @row-click="handleRowClick">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="任务名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="project_name" label="所属项目" min-width="150" show-overflow-tooltip />
      <el-table-column prop="assignee" label="负责人" width="120" />
      <el-table-column prop="priority" label="优先级" width="100">
        <template #default="scope">
          <el-tag :type="getPriorityType(scope.row.priority)">{{ scope.row.priority }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="due_date" label="截止日期" width="120" />
      <el-table-column prop="progress" label="进度" width="180">
        <template #default="scope">
          <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button size="small" @click.stop="editTask(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click.stop="deleteTask(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="totalTasks > pageSize"
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalTasks"
      layout="total, prev, pager, next, jumper"
      @current-change="handlePageChange"
    />

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      :title="taskForm.id ? '编辑任务' : '创建任务'"
      width="50%">
      <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="100px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="taskForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="taskForm.description" type="textarea" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="负责人" prop="assignee">
          <el-select v-model="taskForm.assignee" placeholder="请选择负责人" style="width: 100%">
            <el-option
              v-for="member in members"
              :key="member.id"
              :label="member.name"
              :value="member.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option label="低" value="低" />
            <el-option label="中" value="中" />
            <el-option label="高" value="高" />
            <el-option label="紧急" value="紧急" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="taskForm.status" placeholder="请选择任务状态" style="width: 100%">
            <el-option label="未开始" value="未开始" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已暂停" value="已暂停" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="due_date">
          <el-date-picker v-model="taskForm.due_date" type="date" placeholder="选择截止日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-slider v-model="taskForm.progress" :step="5" show-stops />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTaskForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="taskDetailVisible"
      title="任务详情"
      width="60%">
      <div v-if="selectedTask" class="task-detail">
        <div class="task-detail-header">
          <h2>{{ selectedTask.name }}</h2>
          <div class="task-badges">
            <el-tag :type="getStatusType(selectedTask.status)" class="task-badge">{{ selectedTask.status }}</el-tag>
            <el-tag :type="getPriorityType(selectedTask.priority)" class="task-badge">{{ selectedTask.priority }}</el-tag>
          </div>
        </div>
        
        <div class="task-detail-info">
          <div class="info-item">
            <span class="label">所属项目:</span>
            <span class="value">{{ selectedTask.project_name }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人:</span>
            <span class="value">{{ selectedTask.assignee }}</span>
          </div>
          <div class="info-item">
            <span class="label">截止日期:</span>
            <span class="value">{{ selectedTask.due_date }}</span>
          </div>
          <div class="info-item">
            <span class="label">进度:</span>
            <div class="value progress-bar">
              <el-progress :percentage="selectedTask.progress" :status="getProgressStatus(selectedTask.progress)" />
            </div>
          </div>
          <div class="info-item full-width">
            <span class="label">描述:</span>
            <div class="value description">{{ selectedTask.description || '无描述' }}</div>
          </div>
        </div>
        
        <div class="task-detail-actions">
          <el-button type="primary" @click="editTask(selectedTask)">编辑任务</el-button>
          <el-button @click="taskDetailVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
// import { useStore } from 'vuex'
// import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TasksView',
  setup() {
    // const store = useStore()
    // const router = useRouter()
    const taskFormRef = ref(null)
    
    const loading = ref(true)
    const searchQuery = ref('')
    const filterProject = ref('')
    const filterStatus = ref('')
    const filterPriority = ref('')
    const filterAssignee = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    const taskDialogVisible = ref(false)
    const taskDetailVisible = ref(false)
    const selectedTask = ref(null)
    
    // 任务表单
    const taskForm = reactive({
      id: '',
      name: '',
      project_id: '',
      project_name: '',
      description: '',
      assignee: '',
      priority: '中',
      status: '未开始',
      due_date: '',
      progress: 0
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      project_id: [
        { required: true, message: '请选择所属项目', trigger: 'change' }
      ],
      assignee: [
        { required: true, message: '请选择负责人', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择任务状态', trigger: 'change' }
      ],
      due_date: [
        { required: true, message: '请选择截止日期', trigger: 'change' }
      ]
    }
    
    // 模拟项目数据
    const projects = ref([
      {
        id: 1,
        name: '企业官网重构项目'
      },
      {
        id: 2,
        name: '移动应用开发'
      },
      {
        id: 3,
        name: '数据分析平台'
      }
    ])
    
    // 模拟团队成员数据
    const members = ref([
      {
        id: 1,
        name: '张三'
      },
      {
        id: 2,
        name: '李四'
      },
      {
        id: 3,
        name: '王五'
      },
      {
        id: 4,
        name: '赵六'
      },
      {
        id: 5,
        name: '钱七'
      }
    ])
    
    // 模拟任务数据
    const tasks = ref([
      {
        id: 1,
        name: '需求分析',
        project_id: 1,
        project_name: '企业官网重构项目',
        description: '收集和分析用户需求，确定项目范围',
        assignee: '张三',
        priority: '高',
        status: '已完成',
        due_date: '2023-01-25',
        progress: 100
      },
      {
        id: 2,
        name: '设计系统架构',
        project_id: 1,
        project_name: '企业官网重构项目',
        description: '设计系统整体架构和技术选型',
        assignee: '李四',
        priority: '高',
        status: '已完成',
        due_date: '2023-02-10',
        progress: 100
      },
      {
        id: 3,
        name: '前端开发',
        project_id: 1,
        project_name: '企业官网重构项目',
        description: '实现用户界面和交互功能',
        assignee: '王五',
        priority: '中',
        status: '进行中',
        due_date: '2023-03-15',
        progress: 70
      },
      {
        id: 4,
        name: '后端开发',
        project_id: 1,
        project_name: '企业官网重构项目',
        description: '实现业务逻辑和数据处理',
        assignee: '赵六',
        priority: '中',
        status: '进行中',
        due_date: '2023-03-20',
        progress: 60
      },
      {
        id: 5,
        name: '测试',
        project_id: 1,
        project_name: '企业官网重构项目',
        description: '进行功能测试和性能测试',
        assignee: '钱七',
        priority: '中',
        status: '未开始',
        due_date: '2023-04-10',
        progress: 0
      },
      {
        id: 6,
        name: '需求调研',
        project_id: 2,
        project_name: '移动应用开发',
        description: '调研用户需求和市场情况',
        assignee: '张三',
        priority: '高',
        status: '已完成',
        due_date: '2023-02-10',
        progress: 100
      },
      {
        id: 7,
        name: 'UI设计',
        project_id: 2,
        project_name: '移动应用开发',
        description: '设计移动应用界面和交互',
        assignee: '王五',
        priority: '高',
        status: '进行中',
        due_date: '2023-03-05',
        progress: 80
      },
      {
        id: 8,
        name: '数据库设计',
        project_id: 3,
        project_name: '数据分析平台',
        description: '设计数据库结构和关系',
        assignee: '李四',
        priority: '高',
        status: '已完成',
        due_date: '2022-12-15',
        progress: 100
      },
      {
        id: 9,
        name: '数据可视化开发',
        project_id: 3,
        project_name: '数据分析平台',
        description: '实现数据可视化图表和仪表盘',
        assignee: '王五',
        priority: '中',
        status: '已完成',
        due_date: '2023-01-20',
        progress: 100
      },
      {
        id: 10,
        name: '报表功能开发',
        project_id: 3,
        project_name: '数据分析平台',
        description: '实现自定义报表生成功能',
        assignee: '赵六',
        priority: '中',
        status: '已完成',
        due_date: '2023-02-28',
        progress: 100
      }
    ])
    
    // 筛选后的任务列表
    const filteredTasks = computed(() => {
      let result = tasks.value
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(task => 
          task.name.toLowerCase().includes(query) ||
          task.description.toLowerCase().includes(query)
        )
      }
      
      // 项目过滤
      if (filterProject.value) {
        result = result.filter(task => task.project_id === filterProject.value)
      }
      
      // 状态过滤
      if (filterStatus.value) {
        result = result.filter(task => task.status === filterStatus.value)
      }
      
      // 优先级过滤
      if (filterPriority.value) {
        result = result.filter(task => task.priority === filterPriority.value)
      }
      
      // 负责人过滤
      if (filterAssignee.value) {
        result = result.filter(task => task.assignee === filterAssignee.value)
      }
      
      // 分页
      const startIndex = (currentPage.value - 1) * pageSize.value
      return result.slice(startIndex, startIndex + pageSize.value)
    })
    
    // 总任务数
    const totalTasks = computed(() => {
      let result = tasks.value
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(task => 
          task.name.toLowerCase().includes(query) ||
          task.description.toLowerCase().includes(query)
        )
      }
      
      // 项目过滤
      if (filterProject.value) {
        result = result.filter(task => task.project_id === filterProject.value)
      }
      
      // 状态过滤
      if (filterStatus.value) {
        result = result.filter(task => task.status === filterStatus.value)
      }
      
      // 优先级过滤
      if (filterPriority.value) {
        result = result.filter(task => task.priority === filterPriority.value)
      }
      
      // 负责人过滤
      if (filterAssignee.value) {
        result = result.filter(task => task.assignee === filterAssignee.value)
      }
      
      return result.length
    })
    
    // 获取任务列表
    const fetchTasks = async () => {
      loading.value = true
      try {
        // 实际项目中应该从API获取数据
        // const response = await store.dispatch('task/getTasks')
        // tasks.value = response.data
        
        // 模拟API请求延迟
        setTimeout(() => {
          loading.value = false
        }, 500)
      } catch (error) {
        ElMessage.error('获取任务列表失败')
        loading.value = false
      }
    }
    
    // 显示创建任务对话框
    const showCreateTaskDialog = () => {
      resetTaskForm()
      taskDialogVisible.value = true
    }
    
    // 重置任务表单
    const resetTaskForm = () => {
      taskForm.id = ''
      taskForm.name = ''
      taskForm.project_id = ''
      taskForm.project_name = ''
      taskForm.description = ''
      taskForm.assignee = ''
      taskForm.priority = '中'
      taskForm.status = '未开始'
      taskForm.due_date = ''
      taskForm.progress = 0
      
      if (taskFormRef.value) {
        taskFormRef.value.resetFields()
      }
    }
    
    // 提交任务表单
    const submitTaskForm = () => {
      taskFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 获取项目名称
            const project = projects.value.find(p => p.id === taskForm.project_id)
            if (project) {
              taskForm.project_name = project.name
            }
            
            if (taskForm.id) {
              // 更新任务
              const index = tasks.value.findIndex(t => t.id === taskForm.id)
              if (index !== -1) {
                tasks.value[index] = { ...taskForm }
              }
              ElMessage.success('更新任务成功')
            } else {
              // 创建任务
              const newTask = {
                ...taskForm,
                id: tasks.value.length + 1
              }
              tasks.value.push(newTask)
              ElMessage.success('创建任务成功')
            }
            taskDialogVisible.value = false
          } catch (error) {
            ElMessage.error(taskForm.id ? '更新任务失败' : '创建任务失败')
          }
        }
      })
    }
    
    // 编辑任务
    const editTask = (task) => {
      Object.assign(taskForm, task)
      taskDialogVisible.value = true
      if (taskDetailVisible.value) {
        taskDetailVisible.value = false
      }
    }
    
    // 删除任务
    const deleteTask = (task) => {
      ElMessageBox.confirm(
        '确定要删除该任务吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        const index = tasks.value.findIndex(t => t.id === task.id)
        if (index !== -1) {
          tasks.value.splice(index, 1)
        }
        ElMessage.success('删除任务成功')
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 处理行点击事件
    const handleRowClick = (row) => {
      selectedTask.value = row
      taskDetailVisible.value = true
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    // 处理搜索清除
    const handleSearchClear = () => {
      searchQuery.value = ''
    }
    
    // 监听筛选条件变化，重置页码
    watch([searchQuery, filterProject, filterStatus, filterPriority, filterAssignee], () => {
      currentPage.value = 1
    })
    
    // 获取状态对应的类型
    const getStatusType = (status) => {
      const statusMap = {
        '未开始': 'info',
        '进行中': 'primary',
        '已完成': 'success',
        '已暂停': 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取优先级对应的类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        '低': 'info',
        '中': 'warning',
        '高': 'danger',
        '紧急': 'danger'
      }
      return priorityMap[priority] || 'info'
    }
    
    // 获取进度对应的状态
    const getProgressStatus = (progress) => {
      if (progress >= 100) return 'success'
      if (progress >= 80) return 'success'
      if (progress >= 50) return ''
      if (progress >= 20) return 'warning'
      return 'exception'
    }
    
    onMounted(() => {
      fetchTasks()
    })
    
    return {
      loading,
      tasks,
      projects,
      members,
      filteredTasks,
      totalTasks,
      searchQuery,
      filterProject,
      filterStatus,
      filterPriority,
      filterAssignee,
      currentPage,
      pageSize,
      taskForm,
      taskFormRef,
      rules,
      taskDialogVisible,
      taskDetailVisible,
      selectedTask,
      showCreateTaskDialog,
      submitTaskForm,
      editTask,
      deleteTask,
      handleRowClick,
      handlePageChange,
      handleSearchClear,
      getStatusType,
      getPriorityType,
      getProgressStatus
    }
  }
}
</script>

<style scoped>
.tasks-container {
  padding: 20px;
}

.tasks-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.tasks-filters {
  display: flex;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.task-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.task-detail-header h2 {
  margin: 0;
}

.task-badges {
  display: flex;
}

.task-badge {
  margin-left: 10px;
}

.task-detail-info {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.info-item {
  width: 33.33%;
  margin-bottom: 15px;
  display: flex;
}

.info-item.full-width {
  width: 100%;
}

.info-item .label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.info-item .value {
  flex: 1;
}

.info-item .progress-bar {
  width: 200px;
}

.info-item .description {
  white-space: pre-line;
}

.task-detail-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>